<template>
  <div class="global-container">
    <div class="global-header">
      <img
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/current.png')"
      />
      <div class="title">
        服务包
        <div class="title-content">
          提供服务包管理能力，支持用户对服务包的导入、导出、检索、部署等功能。
        </div>
      </div>
    </div>
    <div class="global-info">
      <div class="global-operate">
        <span class="keyword">关键词：</span>
        <el-input
          v-model="searchInput"
          placeholder="请输入服务包名称或标签检索"
          clearable
          class="inputStyle"
          style="width: 20%"
          prefix-icon="el-icon-search"
          @input="filterAppInfoListByAppNameOrAppZhName"
        />
        <el-tooltip class="item" effect="dark" content="标签管理" placement="top">
          <el-button type="primary" class="el-button-primary-style" icon="el-icon-collection-tag" circle size="small" @click="openAddAppTagDialog" placeholder="标签管理"></el-button>
        </el-tooltip>

        <div class="right-menu">
          <el-button
            v-if="!showCollection"
            type="primary"
            @click="uploadDialogVisible = true"
            class="el-button-primary-style"
          >导入
          </el-button>
          <el-button
            v-if="showCollection"
            @click="unShowMyCollection"
            class="el-button-primary-style"
            style="color: #fff"
          >返回
          </el-button>
          <el-button
            @click="downloadServicePackages"
            class="el-button-primary-style"
            style="color: #fff"
          >批量下载
          </el-button>
          <el-button
            @click="exportServicePackages"
            class="el-button-primary-style"
            style="color: #fff"
          >批量导出
          </el-button>
          <el-button
            @click="importServicePackages"
            class="el-button-primary-style"
            style="color: #fff"
          >批量导入
          </el-button>
        </div>

        <div
          class="collection"
          v-if="!showCollection"
          @click="showMyCollection"
        >
          <el-button
            style="
              /* padding-right: 5px; */
              width: 100px;
              color: #fff;
              margin-right: 10px;
            "
            class="el-button-primary-style"
          >
            <i class="el-icon-star-off" style="color: white"></i>
            我的收藏
          </el-button>
        </div>
      </div>
    </div>

    <div class="servicePackageList">
      <!--        <ServicePackageCard></ServicePackageCard>-->
      <div>
        <div class="cardDiv">
          <el-card
            v-for="(appIn, index) in appInfoList"
            :key="appIn.id"
            class="my-box-card"
          >
            <div slot="header" class="clearfix1">
              <el-checkbox  :id="appIn.id" :name="appIn.id" @change="changeSelectList(appIn.id)"></el-checkbox>
              <div class="imgTopLeft">
                <img
                  :src="appIn.appIcon ? appIn.appIcon : defaultImg"
                  class="imgDiv"
                  @error="handleImageError"
                  style="margin-top: 50%"
                />
                <!-- <img
                  src="../../assets/401_images/401.gif"
                  :title="appIn.id"
                  :alt="appIn.appName"
                  class="imgDiv"
                  v-else
                /> -->
              </div>
              <div class="topRight">
                <div class="everyTab descSpan">
                  <span>名称：</span>
                  <span>{{ appIn.appZhname }}</span>
                </div>
                <!--                <div class="everyTab descSpan">-->
                <!--                  <span>标识：</span>-->
                <!--                  <span>{{ appIn.appName }}</span>-->
                <!--                </div>-->
                <div
                  class="everyTab"
                  style="display: flex; align-items: center;width: 230px"
                >
                  <span>版本：</span>
                  <el-select
                    v-model="appIn.appVersion"
                    size="mini"
                    @focus="getAppInfoVersionList(appIn.appName)"
                    @change="getAppInfoByAppNameAndVersion(appIn, index)"
                  >
                    <el-option
                      v-for="item in appInfoVersionList"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </div>
                <div class="everyTab"
                     style="display: flex; align-items: center;width: 230px">
                  <span>标签：</span>
                  <el-select
                    v-model="appIn.tags"
                    filterable
                    size="mini"
                    placeholder="请选择标签"
                    :multiple-limit=3
                    collapse-tags
                    @focus="getAppTagList()"
                    @change="changeAppTag(appIn)"
                    multiple
                  >
                    <el-option
                      v-for="item in appTagList"
                      :key="item.tagName"
                      :label="item.tagName"
                      :value="item.tagName"
                    >
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>
            <div class="cardDescribeDiv">
              <el-tooltip placement="top-start">
                <div slot="content" style="width: 320px; font-size: 12px">
                  {{ appIn.appDescription }}
                </div>
                <span>
                  {{ appIn.appDescription }}
                </span>
              </el-tooltip>
            </div>
            <div class="operatorDiv">
              <span @click="collectionChanging(appIn, index)">
                <i
                  class="el-icon-star-on"
                  style="padding-top: 4px; font-size: 26px"
                  v-if="appIn.favoriteIndicator === 'true'"
                ></i>
                <i
                  class="el-icon-star-off"
                  style="padding-top: 4px; font-size: 26px"
                  v-if="appIn.favoriteIndicator === 'false'"
                ></i>
              </span>
              <el-button
                type="primary"
                size="small"
                @click="deployService(appIn)"
                class="el-button-primary-style"
              >部署
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="packageDetailInfo(appIn)"
                class="el-button-primary-style"
              >详情
              </el-button>
              <el-dropdown
                class="elDropdown"
                trigger="click"
                @command="
                  (command) => {
                    handleCommand(command, appIn);
                  }
                "
                :hide-on-click="false"
              >
                <el-button
                  type="primary"
                  size="small"
                  class="el-button-primary-style"
                >
                  <i class="el-icon-more"/>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="export">
                    <i class="el-icon-download">导出</i>
                  </el-dropdown-item>
                  <el-popconfirm
                    title="确认删除此服务包数据？"
                    @confirm="deleteServicePackage(appIn)"
                  >
                    <el-dropdown-item slot="reference" style="color: #f56c6c">
                      <i class="el-icon-delete"> 删除 </i>
                    </el-dropdown-item>
                  </el-popconfirm>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-card>
        </div>
      </div>
      <div style="margin-top: 10px; float: right">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="page.total"
          :page-size="page.pageSize"
          :page.sync="page"
          @current-change="changePage"
        />
      </div>
    </div>
    <div>
      <el-dialog
        title="导入服务包"
        :visible.sync="uploadDialogVisible"
        width="30%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <div>
          <el-upload
            class="uploadDiv"
            :action="uploadPath"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            :limit="1"
            :file-list="fileList"
            accept=".tar"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :disabled="fileList.length === 1"
            :destroy-on-close="true"
          >
            <el-button
              size="small"
              type="primary"
              class="el-button-primary-style"
            >点击上传
            </el-button>
            <div slot="tip" class="el-upload__tip">
              文件格式：.tar，单个文件不能超过2048MB
            </div>
          </el-upload>
        </div>
        <div style="margin-top: 15px">
          <h2>日志信息</h2>
          <div class="logDetailsDiv">
            <div v-for="(msg, index) in msgArray" :key="index">
              {{ msg }}
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            @click="closeUploadDialog"
            class="el-button-primary-style"
          >关 闭</el-button
          >
        </span>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="标签管理"
        :visible.sync="addAppTagDialog"
        width="670px"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :before-close="beforeCloseAddAppTagDialog"
      >
        <add-app-tag-dialog
          ref="addDialogRef"
        ></add-app-tag-dialog>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import * as uuid from "uuid";
  import {Subject} from "rxjs";
  import AddAppTagDialog from '@/views/appstore/AddAppTagDialog.vue'

  export default {
    name: "ServicePackage",
    components: { AddAppTagDialog },
    data() {
      return {
        searchInput: "",
        showCollection: false,
        appInfoList: [],
        uploadDialogVisible: false,
        addAppTagDialog: false,
        fileList: [],
        page: {
          pageSize: 8,
          currentPage: 1,
          total: 0,
        },
        tmpPage: {
          pageSize: 8,
          pageNum: 1,
          filterKey: "",
        },
        favorite: {
          id: "",
          type: "",
        },
        baseUploadPath: "/appstore/appinfo/upload/",
        uploadPath: "/appstore/appinfo/upload/",
        topic: "",
        msgArray: [],
        appInfoVersionList: [], //选择的服务表ID列表
        selectAppInfoList: [],
        appTagList: [], //服务包标签列表
        defaultImg: require("@/assets/servicePackage/default2.png"),
        packageSharePath: "" //服务包共享路径，用于批量导入和批量导出
        // "https://wpimg.wallstcn.com/69a1c46c-eb1c-4b46-8bd4-e9e686ef5251.png",
      };
    },
    beforeMount() {
      this.getAppInfoList();
      this.topic = uuid.v4();
      this.uploadPath = this.baseUploadPath + this.topic + "?appType=0";
    },
    methods: {
      getAppInfoList() {
        this.$appStoreApi
          .getAppInfoListByPage(this.tmpPage)
          .then((res) => {
            if (res && res.code === 200) {
              this.appInfoList = res.data.records;
              this.page.total = res.data.total;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      //服务包卡片左上角勾选触发操作
      changeSelectList(id) {
        if (this.selectAppInfoList.length === 0) {
          this.selectAppInfoList.push(id);
        } else {
          let index = -1;
          for (let i = 0; i < this.selectAppInfoList.length; i++) {
            if (this.selectAppInfoList[i] === id) {
              index = i;
              break;
            }
          }
          if (index === -1) {
            this.selectAppInfoList.push(id);
          } else {
            this.selectAppInfoList.splice(index, 1);
          }
        }
        console.log("selected list",this.selectAppInfoList)
      },
      //批量下载服务包到本地
      downloadServicePackages() {
        if(this.selectAppInfoList.length === 0) {
          this.$message.error("请选择要下载的服务包");
        }
        for(let i = 0; i < this.selectAppInfoList.length; i++) {
          window.open(`/appstore/appinfo/download/${this.selectAppInfoList[i]}`);
        }
      },
      //批量导出服务包到共享区域
      exportServicePackages() {
        if(this.selectAppInfoList.length === 0) {
          this.$message.error("请选择要导出的服务包");
        }
        this.$storagePvcApi.getAppStorePvPath().then((res) => {
          if (res && res.code === 200) {
            this.packageSharePath = res.data;
          }
        }).catch((error) => {
          this.$message.error(error.message);
        });
        this.$appStoreApi
          .exportServicePackages(this.selectAppInfoList)
          .then((res) => {
            if (res && res.code === 200) {
              //如果成功导出服务包到共享区域，则提示成功并返回共享路径，否则提示失败
              this.$message.success("导出成功，服务包已保存到共享路径：" + this.packageSharePath);
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      //共享区域批量导入服务包
      importServicePackages() {
        this.$storagePvcApi.getAppStorePvPath().then((res) => {
          if (res && res.code === 200) {
            this.packageSharePath = res.data;
          }
        }).catch((error) => {
          this.$message.error(error.message);
        });
        this.$alert("请确认已将需要导入的服务包放入路径：" + this.packageSharePath, "共享区域批量导入", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {
            if (action === "confirm") {
              this.$appStoreApi
                .importServicePackages()
                .then((res) => {
                  if (res && res.code === 200) {
                    this.$message.success(res.data);
                    this.getAppInfoList();
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
            }
          },
        });
      },
      getFavoriteInfoList() {
        this.$appStoreApi
          .pageListPackageFavorite(this.tmpPage)
          .then((res) => {
            console.log(res);
            if (res && res.code === 200) {
              this.appInfoList = res.data.records;
              this.page.total = res.data.total;
            }
            console.log(this.appInfoList);
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      unShowMyCollection() {
        this.showCollection = false;
        this.getAppInfoList();
      },
      showMyCollection() {
        this.showCollection = true;
        this.getFavoriteInfoList();
      },
      collectionChanging(appIn, index) {
        this.favorite.id = appIn.id;
        if (appIn.favoriteIndicator === "true") {
          this.favorite.type = "false";
          this.$message.success("取消收藏");
        } else {
          this.favorite.type = "true";
          this.$message.success("收藏成功");
        }
        this.$appStoreApi
          .favoritePackage(this.favorite)
          .then((res) => {
            if (res && res.code === 200) {
              if (appIn.favoriteIndicator === "true") {
                this.appInfoList[index].favoriteIndicator = "false";
              } else {
                this.appInfoList[index].favoriteIndicator = "true";
              }
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      handleImageError(event) {
        event.target.src = this.defaultImg;
      },
      filterAppInfoListByAppNameOrAppZhName() {
        console.log(111);
        this.tmpPage.filterKey = this.searchInput;
        this.tmpPage.pageNum = 1;
        this.tmpPage.pageSize = 8;
        if (this.showCollection) {
          this.getFavoriteInfoList();
        } else {
          this.getAppInfoList();
        }
      },
      // keyi
      changePage(currentPage) {
        this.page.currentPage = currentPage;
        this.tmpPage.pageNum = currentPage;
        this.getAppInfoList();
      },
      deployService(appIn) {
        this.$router.push({
          name: "ServiceDeploy",
          params: {
            id: appIn.id,
            appVersion: appIn.appVersion,
            appName: appIn.appName,
          },
        });
      },
      packageDetailInfo(appIn) {
        this.$router.push({
          name: "ServicePackageDetail",
          params: {
            id: appIn.id,
            appVersion: appIn.appVersion,
            appName: appIn.appName,
          },
        });
      },
      deleteServicePackage(row) {
        this.$appStoreApi
          .deletePackage(row.id)
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.data);
              this.getAppInfoList();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      handleCommand(command, appInfo) {
        if (command === "delete") {
          this.$alert("确认删除此服务实例", "删除服务实例", {
            confirmButtonText: "确定",
            type: "warning",
            callback: (action) => {
              if (action === "confirm") {
                this.$appStoreApi
                  .deletePackage(appInfo.id)
                  .then((res) => {
                    if (res && res.code === 200) {
                      this.$message.success(res.data);
                      this.getAppInfoList();
                    }
                  })
                  .catch((error) => {
                    this.$message.error(error.message);
                  });
              }
            },
          });
        } else if (command === "export") {
          window.open(`/appstore/appinfo/download/${appInfo.id}`);
        }
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      closeUploadDialog() {
        this.fileList = [];
        this.uploadDialogVisible = false;
        this.msgArray = [];
        this.getAppInfoList();
      },
      beforeUpload(file) {
        const isLt2G = file.size / 1024 / 1024 < 2048;
        if (!isLt2G) {
          this.$message.error("上传文件大小不能超过 2048MB!");
        }
        this.openMessage();
        return isLt2G;
      },
      onUploadSuccess(res) {
        if (res && res.code === 200) {
          this.$message.success("文件上传成功");
        } else {
          this.$message.error("文件上传失败：" + res.msg);
          this.fileList = [];
        }
        // const fd = new FormData();
        // fd.append("file",file);
        // this.$appStoreApi.uploadPackage(fd).then(res => {
        //   console.log(res)
        // });
      },
      onUploadError(error) {
        this.$message.error("文件上传失败：" + error);
      },
      openMessage() {
        this.msgArray = [];
        let subs = new Subject();
        let eventSource = new EventSource(`/appstore/webflux/sse/${this.topic}`);
        let first = true;
        eventSource.onmessage = (e) => {
          if (!first) {
            subs.next(e.data);
          } else {
            first = false;
          }
        };
        eventSource.onerror = (e) => {
          eventSource.close();
        };
        subs.subscribe((msg) => {
          this.msgArray.unshift(msg);
        });
      },
      getAppInfoVersionList(appName) {
        this.$appStoreApi
          .appNameVersionList(appName)
          .then((res) => {
            if (res && res.code === 200) {
              this.appInfoVersionList = res.data;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      getAppInfoByAppNameAndVersion(appInfo, index) {
        const param = {
          appName: appInfo.appName,
          appVersion: appInfo.appVersion,
        };
        this.$appStoreApi
          .appInfoByAppNameAndVersion(param)
          .then((res) => {
            if (res && res.code === 200) {
              // this.appInfoList[index] = res.data;
              this.$set(this.appInfoList, index, res.data);
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      //关闭添加标签弹窗之前的操作
      beforeCloseAddAppTagDialog() {
        this.addAppTagDialog = false;
        this.$refs.addDialogRef.resetForm();
      },
      //打开添加标签弹窗操作
      openAddAppTagDialog() {
        this.addAppTagDialog = true;
        this.$nextTick(() => {
          if (this.$refs.addDialogRef !== undefined) {
            this.$refs.addDialogRef.$on(
              "beforeCloseAddAppTagDialog",
              this.beforeCloseAddAppTagDialog
            );
          }
        });
      },
      //获取所有标签列表
      getAppTagList() {
        this.$appStoreApi
          .listAppTag()
          .then((res) => {
            if (res && res.code === 200) {
              this.appTagList = res.data;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      //修改应用标签
      changeAppTag(appIn) {
        this.$appStoreApi
          .tagPackage({
            tags: appIn.tags == null? [] : appIn.tags,
            id: appIn.id,
          })
          .then((res) => {
            if (res && res.code === 200) {
              this.getAppInfoList();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          })
      },
    },
  };
</script>

<style lang="css" scoped>
  .collection {
    display: flex;
    /* align-items: center;
          justify-content: center; */
    float: right;
    /* margin-right: 30px;
          font-size: 20px;
          padding-top: 10px; */
  }

  .imgDiv {
    height: 45px;
    width: 45px;
    border-radius: 40px;
    margin-right: 10px;
  }

  .topRight {
    width: 250px;
    font-size: 15px;
  }

  .everyTab {
    margin-top: 7px;
  }

  .elDropdown {
    vertical-align: top;
    margin-left: 10px;
  }

  .uploadDiv {
    height: 100px;
  }

  .logDetailsDiv {
    border: 1px solid #ededed;
    height: 150px;
    overflow-y: scroll;
  }

  /*::v-deep .el-button--primary {*/
  /*  background-color: #304156;*/
  /*  border-color: #304156;*/
  /*}*/

  /*.el-button {*/
  /*  border-radius: 30px;*/
  /*  display: inline-block;*/
  /*  margin: 0 8px;*/
  /*}*/

  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #304156;
  }
</style>
